package com.example.securitymy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.securitymy.domain.LoginUser;
import com.example.securitymy.domain.User;
import com.example.securitymy.mapper.MenuMapper;
import com.example.securitymy.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper wrapper = new LambdaQueryWrapper<User>().eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);
        System.out.println("这是loadUserByUsername=============================");
        System.out.println(user);
        //如果没有该用户就抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //TODO: 查询权限信息封装到LoginUser中
        // 现在是写死的权限
//        ArrayList<String> list = new ArrayList<>();
//        list.add("user");
        //从数据库中获取权限
        List<String> list = menuMapper.selectPermsByUserId(user.getId());

        // 将用户信息封装到UserDetails实现类中
        LoginUser loginUser=new LoginUser(user, (ArrayList<String>) list);
        System.out.printf("loginuser中的属性");
        System.out.println(loginUser.getUsername());
        System.out.println(loginUser.getPassword());
        System.out.println(loginUser.getAuthorities());
        return loginUser;
    }
}
